package com.work.formaldehyde;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.google.gson.Gson;
import com.work.formaldehyde.homefragment.JianceFragment;
import com.work.formaldehyde.homefragment.KepuFragment;
import com.work.formaldehyde.homefragment.TianqiFragment;
import com.work.formaldehyde.homefragment.WodeFragment;
import com.work.formaldehyde.model.FenXiangModel;
import com.work.formaldehyde.model.MoRenDiZhiModel;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.Url;
import com.work.formaldehyde.util.ViewPagerAdapter;
import com.work.formaldehyde.view.MyViewPager;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        ChangeColor(0);
    }

    public static RelativeLayout tianqirela, kepurela, jiancerela, woderela;
    public static TextView tianqitext, keputext, jiancetext, wodetext;
    public static ImageView tianqiicon, kepuicon, jianceicon, wodeicon;
    public static MyViewPager home_pager;

    //存放fragment
    List<Fragment> aryfrag;
    //创建ViewPager适配器
    private ViewPagerAdapter pagerAdapter;
    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor mEditor;
    /**
     * 加载方法
     */
    public void init() {
        setStatusBarFullTransparent();
        setFitSystemWindow(false);
        home_pager = findViewById(R.id.home_pager);
        tianqirela = findViewById(R.id.tianqirela);
        kepurela = findViewById(R.id.kepurela);
        jiancerela = findViewById(R.id.jiancerela);
        woderela = findViewById(R.id.woderela);
        tianqirela.setOnClickListener(this);
        kepurela.setOnClickListener(this);
        jiancerela.setOnClickListener(this);
        woderela.setOnClickListener(this);
        tianqitext = findViewById(R.id.tianqitext);
        keputext = findViewById(R.id.keputext);
        jiancetext = findViewById(R.id.jiancetext);
        wodetext = findViewById(R.id.wodetext);
        tianqiicon = findViewById(R.id.tianqiicon);
        kepuicon = findViewById(R.id.kepuicon);
        jianceicon = findViewById(R.id.jianceicon);
        wodeicon = findViewById(R.id.wodeicon);
        SetViewPage();
        if (!Url.USER_ID.equals("")) {
            okHttp_postFromParameter();
        }
        okHttp_getfenxiang();
        mSharedPreferences = getSharedPreferences("login", MODE_PRIVATE);  //名称和类型
        mEditor = mSharedPreferences.edit();
        mEditor.putString("islogin", "1");
        mEditor.apply();
        mEditor.commit();
    }

    private final int REQUEST_CODE_ADDRESS = 100;
//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        switch (requestCode) {
//            case REQUEST_CODE_ADDRESS:
//                if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] ==PackageManager.PERMISSION_GRANTED) {
//                    // Permission Granted 授予权限
//                    //处理授权之后逻辑
//                    Toast.makeText(this,"一开开！",Toast.LENGTH_LONG).show();
//                } else {
//                    Toast.makeText(this,"定位服务被禁止，位保证软件正常运行。请手动开起！",Toast.LENGTH_LONG).show();
//                }
//
//                break;
//            default:
//                break;
//        }
//
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//    }


    /**
     * 全透状态栏
     */
    public void setStatusBarFullTransparent() {
        if (Build.VERSION.SDK_INT >= 21) {//21表示5.0
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= 19) {//19表示4.4
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //虚拟键盘也透明
            //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    public View contentViewGroup;

    public void setFitSystemWindow(boolean fitSystemWindow) {
        if (contentViewGroup == null) {
            contentViewGroup = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
        }
        contentViewGroup.setFitsSystemWindows(fitSystemWindow);
    }

    /**
     * 将fragment绑定到viewpager
     */
    public void SetViewPage() {
        aryfrag = new ArrayList<>();
        aryfrag.add(new TianqiFragment());
        aryfrag.add(new KepuFragment());
        aryfrag.add(new JianceFragment());
        aryfrag.add(new WodeFragment());
        //绑定点击事件
        home_pager.setOnPageChangeListener(new MyPagerChangeListener());
        //绑定适配器
        pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), aryfrag);
        home_pager.setAdapter(pagerAdapter);
        home_pager.setCurrentItem(0);
        home_pager.setOffscreenPageLimit(4);
    }

    public class MyPagerChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            ChangeColor(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    }


    /**
     * 改变颜色状态
     *
     * @param i 为viewpager的下标，通过下标改变导航栏字体图标
     */
    public  void ChangeColor(int i) {
        if (i == 0) {
            tianqiicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.tqc));
            kepuicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.kp));
            jianceicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.jc));
            wodeicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.wd));
            tianqitext.setTextColor(getResources().getColor(R.color.home_bottom_text_color_ischeck));
            keputext.setTextColor(getResources().getColor(R.color.home_bottom_text_color_oncheck));
            jiancetext.setTextColor(getResources().getColor(R.color.home_bottom_text_color_oncheck));
            wodetext.setTextColor(getResources().getColor(R.color.home_bottom_text_color_oncheck));
        } else if (i == 1) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            tianqiicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.tq));
            kepuicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.kpc));
            jianceicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.jc));
            wodeicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.wd));
            tianqitext.setTextColor(getResources().getColor(R.color.home_bottom_text_color_oncheck));
            keputext.setTextColor(getResources().getColor(R.color.home_bottom_text_color_ischeck));
            jiancetext.setTextColor(getResources().getColor(R.color.home_bottom_text_color_oncheck));
            wodetext.setTextColor(getResources().getColor(R.color.home_bottom_text_color_oncheck));
        } else if (i == 2) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            tianqiicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.tq));
            kepuicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.kp));
            jianceicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.jcc));
            wodeicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.wd));
            tianqitext.setTextColor(getResources().getColor(R.color.home_bottom_text_color_oncheck));
            keputext.setTextColor(getResources().getColor(R.color.home_bottom_text_color_oncheck));
            jiancetext.setTextColor(getResources().getColor(R.color.home_bottom_text_color_ischeck));
            wodetext.setTextColor(getResources().getColor(R.color.home_bottom_text_color_oncheck));
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            tianqiicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.tq));
            kepuicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.kp));
            jianceicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.jc));
            wodeicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.wdc));
            tianqitext.setTextColor(getResources().getColor(R.color.home_bottom_text_color_oncheck));
            keputext.setTextColor(getResources().getColor(R.color.home_bottom_text_color_oncheck));
            jiancetext.setTextColor(getResources().getColor(R.color.home_bottom_text_color_oncheck));
            wodetext.setTextColor(getResources().getColor(R.color.home_bottom_text_color_ischeck));
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tianqirela:
                home_pager.setCurrentItem(0);
                ChangeColor(0);
                break;
            case R.id.kepurela:
                home_pager.setCurrentItem(1);
                ChangeColor(1);
                break;
            case R.id.jiancerela:
                home_pager.setCurrentItem(2);
                ChangeColor(2);
                break;
            case R.id.woderela:
                home_pager.setCurrentItem(3);
                ChangeColor(3);
                break;
        }
    }

    private void okHttp_postFromParameter() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
//                    RequestBody formBody;
//                    Request request;
//                    formBody = new FormBody.Builder().add("uid", Url.USER_ID)
//                            .build();
//                    request = new Request.Builder().url(Url.GETMORENDIZHI).post(formBody).build();
//                    okhttp3.Response response = okHttpClient.newCall(request).execute();
//                    String msg = response.body().string();
//                    Message message = new Message();
//                    message.obj = msg;
//                    gethot1s.sendMessage(message);
                    Request request = new Request.Builder().get().url(Url.MORENADDRESS + Url.USER_ID+"&logintoken="+Url.LOGIN_TOKEN).build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }

                        @Override
                        public void onResponse(Call call, final Response response) {
                            try {
                                final String responseStr;
                                responseStr = response.body().string();
                                Message message = new Message();
                                message.obj = responseStr;
                                gethot1s.sendMessage(message);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    MoRenDiZhiModel shangPingModel;
    public Handler gethot1s = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        shangPingModel = gson.fromJson(msg.obj.toString(),
                                MoRenDiZhiModel.class);
                        Url.MORENDIZHI = shangPingModel.getData().getConsignee_addr();
                        Url.MORENNAME = shangPingModel.getData().getConsignee_name();
                        Url.MORENPHONE = shangPingModel.getData().getConsignee_phone();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


    private void okHttp_getfenxiang() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
//                    RequestBody formBody;
//                    Request request;
//                    formBody = new FormBody.Builder().add("uid", Url.USER_ID)
//                            .build();
//                    request = new Request.Builder().url(Url.GETFENXIANG).post(formBody).build();
//                    okhttp3.Response response = okHttpClient.newCall(request).execute();
//                    String msg = response.body().string();
//                    Message message = new Message();
//                    message.obj = msg;
//                    getfenxiang.sendMessage(message);
                    Request request = new Request.Builder().get().url(Url.SHARE).build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }

                        @Override
                        public void onResponse(Call call, final Response response) {
                            try {
                                final String responseStr;
                                responseStr = response.body().string();
                                Message message = new Message();
                                message.obj = responseStr;
                                getfenxiang.sendMessage(message);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    FenXiangModel fxModel;
    public Handler getfenxiang = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        fxModel = gson.fromJson(msg.obj.toString(),
                                FenXiangModel.class);
                        Url.FENXIANG_TITLE = fxModel.getData().get(0).getTitle();
                        Url.FENXIANG_IMG = fxModel.getData().get(0).getImage();
                        Url.FENXIANG_URL = fxModel.getData().get(0).getUrl2();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


}
